// pages/shop-list/list/index.js

import { getMemberById } from '@/api/member'
import { getNearShopList, updateCollectShopIds } from '@/api/shop'
import { hideLoading, msg, showLoading } from '@/utils/util'
import { toShoppingPage } from '@/utils/page'

Component({

  options: {
    addGlobalClass: true // 使用全局样式
  },

  properties: {
    tabName: String, // 当前所在的标签名 near附近，collect收藏
    longitude: Number, // 地理位置经度
    latitude: Number,// 地理位置纬度
    tabsTop: Number, // 距离顶部的高度
  },

  data: {
    loading: false,
    collectShopIds: [], // 收藏的门店ids
    shopList: [], // 门店列表数据
  },

  /* lifetimes: {
        attached() {
          this.getCollectShopIds()
        }
    },*/
    
  methods: {

    // 查询当前用户已收藏的门店ids
    async getCollectShopIds() {
      const {member} =  getApp().current()
      if (!member || !member._id) return
      // 查询会员，collectShopIds字段保存了收藏的门店ids
      const { data } = await getMemberById(member._id)
      this.setData({ collectShopIds: data.collectShopIds || [] })
      console.log("getCollectShopIds", data)
    },

    // 查询门店列表
    async loadShopList () {
      try {
        this.setData({ loading: true })

        // 1. 查询当前用户已收藏的门店ids
        await this.getCollectShopIds()
        
        // 2. 根据当前用户位置，查询距离由近到远的门店列表数据
        const { tabName, longitude, latitude, collectShopIds } = this.data
        let shopList = [] // 门店列表数据
        if (tabName == 'near') {
          // 查询附近门店
          const { list } = await getNearShopList(longitude, latitude)
          shopList = list
        } else if (collectShopIds && collectShopIds.length > 0) {
          // 查询收藏门店
          const { list } = await getNearShopList(longitude, latitude, collectShopIds)
          shopList = list
        }

        // 数据格式转换：将m转成km
        shopList.forEach(item => {
          // 将m转成km , 
          const distance = Math.round(item.distance || 0)
          item.distanceStr = distance < 1000 ? distance + 'm' : (distance/1000).toFixed(2) + 'km'
          // 判断是否此门店是否已收藏, true已收藏，false未收藏
          item.collected = collectShopIds.includes(item._id)
        })

        this.setData({ shopList: shopList })

        console.log("loadShopListxxxxx", shopList)

        // 3. 更新地图上标点信息
        this.triggerEvent('updateMapMarkers', { shopList })
      } catch (error) {
        console.error('查询门店列表异常', error)
        msg('门店查询失败')
      } finally {
        this.setData({ loading: false })
      }
    },

    // 收藏门店
    async handleCollect(e) {
      try {
        showLoading()

        // 判断是否登录, 未登录会跳转到登录页
        const { logined, member } = getApp().current(true)
        if (!logined) return 

        // 更新操作
        const {item} = e.currentTarget.dataset
        // 取反: 原来是收藏则为取消收藏，反之添加收藏
        const collected = !item.collected
        await updateCollectShopIds(member._id, item._id, collected)    

        // 重新刷新列表数据
        await this.loadShopList()

        msg(collected ? '收藏成功': '已取消收藏', {icon: 'success'})
        console.log('handleCollect', item)
      } catch (error) {
        console.error("收藏失败", error)
        msg('操作失败', {icon: 'error'})
      } finally {
        hideLoading()
      }

    },

    // 打开地图导航页
    handleLocation(e) {
      // console.log('handleLocation', e)
      const { location, name, address } = e.currentTarget.dataset.item
      wx.openLocation({
        longitude: location.coordinates[0],
        latitude: location.coordinates[1],
        name,
        address
      })
    },
      
    // 打电话
    handleCall(e) {
      // console.log('handleCall', e)
      const { contactPhone } = e.currentTarget.dataset.item
      if (!contactPhone) return msg('无联系电话')
      // 调用打电话api
      wx.makePhoneCall({
        phoneNumber: contactPhone
      })
    },

    // 去下单页
    toShoppingPage(e) {
      console.log('toShoppingPage', e)
      const { shop } = e.currentTarget.dataset
      toShoppingPage({ shop })
    }

  }

})